package org.uugu.counter.Support;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * SQLite DB工具类
 * Created by Silence on 2014/3/29.
 */
public class DatabaseUtils extends SQLiteOpenHelper {

    public DatabaseUtils(Context context, String name, int version) {
        super(context, name, null, version);
    }


    @Override
    public void onCreate(SQLiteDatabase db) {

        db.execSQL("CREATE TABLE \"groups\" (\n" +
                "\"id\"  INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,\n" +
                "\"date\"  TEXT,\n" +
                "\"name\"  TEXT\n" +
                ");");

        db.execSQL("CREATE TABLE \"data\" (\n" +
                "\"id\"  INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,\n" +
                "\"width\"  INTEGER,\n" +
                "\"w_num\"  INTEGER,\n" +
                "\"hight\"  INTEGER,\n" +
                "\"h_num\"  INTEGER,\n" +
                "\"group_id\"  INTEGER,\n" +
                "CONSTRAINT \"goupId\" FOREIGN KEY (\"group_id\") REFERENCES \"groups\" (\"id\") ON DELETE CASCADE\n" +
                ");");
    }

    /**
     * 删除数据库
     */
    public void clearTable(SQLiteDatabase db){
        db.execSQL("delete from data;");
        db.execSQL("delete from groups;");
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }

    /**
     * 从Cursor转到List
     * @param cursor
     * @return
     */
    public List<Map<String, String>> converCursorToList(Cursor cursor){
        ArrayList<Map<String, String>> result = new ArrayList<Map<String, String>>();
        // 遍历Cursor取值
        while(cursor.moveToNext()){
            Map<String, String> map = new HashMap<String, String>();
            for(int i = 0; i < cursor.getColumnCount(); i++) {
                map.put(cursor.getColumnName(i), cursor.getString(i));
            }
            result.add(map);
        }
        return result;
    }
}
